package cn.itcast.service.impl;

import cn.itcast.dao.OrderDao;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Order;
import cn.itcast.pojo.OrderSetting;
import cn.itcast.service.OrderService;
import cn.itcast.utils.DateUtils;
import cn.itcast.utils.MD5Utils;
import com.alibaba.dubbo.config.annotation.Service;
import com.sun.corba.se.spi.orb.ParserData;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import static cn.itcast.constant.MessageConstant.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Override
    public Result submit(Order order) {
        System.out.println(order);
        try {
            //获取提交订单的时间

            String orderDate = DateUtils.parseDate2String(order.getOrderDate());

            //根据这个时间去数据库查询
            OrderSetting orderSetting = this.orderDao.findByDate(orderDate);
            //如果查出这一天没有预约设置就直接返回false
            if(null == orderSetting){
                return new Result(false,SELECTED_DATE_CANNOT_ORDER,null);
            }
            //检查已预约人数是否大于等于可预约人数
            boolean flag = orderSetting.getReservations() >= orderSetting.getNumber();
            //符合条件直接返回false
            if(flag){
                return new Result(false,ORDER_FULL,null);
            }

            //检查当前用户是否已经预约过该体检套餐
            //判断条件1.身份证号2.setmeal编号3.预约日期 都符合就已经预约过
            String idCard = order.getIdCard();
            Integer setmealId = order.getSetmealId();
            //如果查到了数据就说明已经预约过了,直接返回false
            if(null != this.orderDao.ExistOrNot(idCard,setmealId,orderDate)){
                return new Result(false,HAS_ORDERED,null);
            }
            //排除掉以上状况之后确认可以提交了就在order表中添加一条数据
            //uuid36位太长,不符合微信api的要求,需要改成32位
            //想到的方法是生成的uuid再MD5加密缩短位数
            String s = UUID.randomUUID().toString();
            String orderId = MD5Utils.md5(s);

            //设置属性
            order.setId(orderId);
            order.setOrderStatus(1);
            order.setArrival(1);
            short married = 1;
            order.setMarried(married);
            order.setPayStatus(0);

            //插入数据
            orderDao.add(order);

        } catch (Exception e) {
            return new Result(false,ORDER_FAIL);
        }
        return new Result(true,ORDER_SUCCESS,order.getId());


    }

    @Override
    public Order findById(String id) {

        return this.orderDao.findById(id);
    }

    @Override
    public List<Order> findUserAll(Integer id) {

        return this.orderDao.findUserAll(id);
    }

    @Override
    public void updatePayStatus(String orderId , short status) {
        this.orderDao.updatePayStatus(orderId,status);
    }
}
